import os
from typing import Annotated

import httpx
from langchain_core.tools import tool


@tool
def get_coordinate(
    address: Annotated[str, "结构化地址信息"],
    city: Annotated[str, "要获取经纬度的地点所在的城市名称,可不填"] = "",
) -> list[dict[str, str]] | str:
    """位置获取工具。根据地点名称和城市名称获取该地点的经纬度。由于可能存在同名地点，
    所以返回的是一个包含所有同名地点详细地址和经纬度的列表"""

    amap_key = os.getenv("AMAP_API_KEY")

    base_url = r"https://restapi.amap.com/v3/geocode/geo"
    params = {
        "key": amap_key,
        "address": address,
        "city": city,
    }

    response = httpx.get(base_url, params=params).json()

    if response["status"] == "0":
        error_msg = f"获取以下地点坐标失败：{address}。错误信息: {response['info']}。"
        return error_msg

    results = []

    for geocode in response["geocodes"]:
        results.append(
            {
                "address": geocode["formatted_address"],
                "coordinate": geocode["location"],
                "city_code": geocode["citycode"],
            }
        )

    return results


if __name__ == "__main__":
    from dotenv import find_dotenv, load_dotenv

    _ = load_dotenv(find_dotenv())
    print(get_coordinate.invoke({"address": "中国地质大学", "city": "武汉"}))
